package com.ebspp.client.serverManager;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

import com.ebspp.global.General;
import com.ebspp.thrift.DataMsg;
import com.ebspp.thrift.Identity;
import com.ebspp.thrift.ResourceType;

public class GarbageConnManager 
{
	int gbPort;
	Map<String, GarbageConnection> serverConnMap;
	
	public GarbageConnManager()
	{
		this.gbPort = General.wPort;
		serverConnMap = Collections.synchronizedMap(new HashMap<String, GarbageConnection>());
	}
	

	public synchronized GarbageConnection createGBConn(String server, ResourceType resType, Identity clientID)
	{		
		GarbageConnection gbConn = serverConnMap.get(server);
		if(gbConn != null)
			return gbConn;
		
		try 
		{
			gbConn = new GarbageConnection(server, gbPort, resType, clientID);
			gbConn.connect();
		
			serverConnMap.put(server, gbConn);
		} 
		catch (TTransportException e) {
			// TODO Auto-generated catch block
			System.err.println("Unable to init garbage connection to " + server + "\n" + e.getMessage());
			e.printStackTrace();
			return null;
		}
		
		return gbConn;
	}
	
	public synchronized boolean closeGBConn(String server)
	{
		GarbageConnection gbConn = serverConnMap.get(server);
		if(gbConn == null)
			return true;
		
		gbConn.close();
		serverConnMap.remove(server);
		return true;
	}
	
	public List<DataMsg> garbageCollect(List<DataMsg> gbs, String server) throws TException
	{
		GarbageConnection gbConn = serverConnMap.get(server);
		if(gbConn == null)
			return gbs;
		
		return gbConn.gbCollect(gbs);
	}
}
